package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * @author ct_start
 * @create 2021 -10 -10
 **/
// 这是一个@Responsebody 是controller 返回json串的注解
    // @ControllerAdvice 是统一异常
@Slf4j
@RestControllerAdvice (basePackages = "com.atguigu.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException (MethodArgumentNotValidException e){ //精准捕捉异常
        log.info("捕捉到的异常信息{},异常类型{}",e.getMessage(),e.getClass()); //代表的是一种占位符
//        System.out.println(e.getMessage()+"异常类"+e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        HashMap<String , String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> map.put(fieldError.getField(),fieldError.getDefaultMessage()));
        return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(),BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException (Throwable throwable){
        System.out.println(throwable.getMessage()+"错误类型"+throwable.getClass());
        return  R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
    }
}
